using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using MaterialDesignThemes.Wpf;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 创作需求对话框
    /// </summary>
    public partial class CreativeRequestDialog : Window
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<CreativeRequestDialog> _logger;
        private readonly IAIService _aiService;
        private bool _isGenerating = false;

        public string? GeneratedContent { get; private set; }
        public bool IsConfirmed { get; private set; }

        public CreativeRequestDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<CreativeRequestDialog>>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();
            
            InitializeUI();
        }

        private void InitializeUI()
        {
            // 设置默认值
            TargetWordCountTextBox.Text = "2000";
            TemperatureSlider.Value = 0.8;
            
            // 更新UI状态
            UpdateUIForCreationType();
        }

        private void CreationType_Checked(object sender, RoutedEventArgs e)
        {
            UpdateUIForCreationType();
        }

        private void UpdateUIForCreationType()
        {
            if (RequestTitle == null) return;

            if (ChapterRadio?.IsChecked == true)
            {
                RequestTitle.Text = "章节创作要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请描述章节的主要情节、角色发展、场景设置等...");
                }
                TargetWordCountTextBox.Text = "6500";
            }
            else if (ContinueRadio?.IsChecked == true)
            {
                RequestTitle.Text = "续写要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请描述需要续写的方向、情节发展、预期结果等...");
                }
                TargetWordCountTextBox.Text = "1500";
            }
            else if (PolishRadio?.IsChecked == true)
            {
                RequestTitle.Text = "润色要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请描述需要润色的重点、风格要求、改进方向等...");
                }
                TargetWordCountTextBox.Text = "0";
            }
            else if (ExpandRadio?.IsChecked == true)
            {
                RequestTitle.Text = "扩写要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请描述需要扩写的内容、详细程度、重点方向等...");
                }
                TargetWordCountTextBox.Text = "3000";
            }
            else if (OutlineRadio?.IsChecked == true)
            {
                RequestTitle.Text = "大纲生成要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请描述故事背景、主要角色、情节走向、章节数量等...");
                }
                TargetWordCountTextBox.Text = "1000";
            }
            else if (CustomRadio?.IsChecked == true)
            {
                RequestTitle.Text = "自定义创作要求";
                if (BasicRequestTextBox != null)
                {
                    HintAssist.SetHint(BasicRequestTextBox, "请详细描述您的创作需求...");
                }
                TargetWordCountTextBox.Text = "2000";
            }
        }

        private async void Generate_Click(object sender, RoutedEventArgs e)
        {
            if (_isGenerating) return;

            try
            {
                _isGenerating = true;
                UpdateGenerationUI(true);

                var prompt = BuildCreativePrompt();
                var targetWordCount = int.TryParse(TargetWordCountTextBox.Text, out var count) ? count : 2000;
                var temperature = (float)TemperatureSlider.Value;

                StatusText.Text = "正在生成内容...";
                
                var content = await _aiService.GenerateTextAsync(prompt, Math.Max(targetWordCount + 500, 1000), temperature);
                
                GeneratedContentTextBox.Text = content;
                GeneratedContent = content;
                
                ApplyButton.IsEnabled = !string.IsNullOrWhiteSpace(content);
                RegenerateButton.IsEnabled = true;
                
                StatusText.Text = "内容生成完成";
                _logger.LogInformation("创作内容生成成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成创作内容失败");
                StatusText.Text = $"生成失败: {ex.Message}";
                MessageBox.Show($"生成内容时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isGenerating = false;
                UpdateGenerationUI(false);
            }
        }

        private async void Regenerate_Click(object sender, RoutedEventArgs e)
        {
            // 重新生成内容
            if (_isGenerating) return;

            try
            {
                _isGenerating = true;
                UpdateGenerationUI(true);

                var prompt = BuildCreativePrompt();
                var targetWordCount = int.TryParse(TargetWordCountTextBox.Text, out var count) ? count : 2000;
                var temperature = (float)TemperatureSlider.Value;

                StatusText.Text = "正在重新生成内容...";

                var content = await _aiService.GenerateTextAsync(prompt, Math.Max(targetWordCount + 500, 1000), temperature);

                GeneratedContentTextBox.Text = content;
                GeneratedContent = content;

                ApplyButton.IsEnabled = !string.IsNullOrWhiteSpace(content);

                StatusText.Text = "内容重新生成完成";
                _logger.LogInformation("创作内容重新生成成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重新生成创作内容失败");
                StatusText.Text = $"重新生成失败: {ex.Message}";
                MessageBox.Show($"重新生成内容时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isGenerating = false;
                UpdateGenerationUI(false);
            }
        }

        private string BuildCreativePrompt()
        {
            var creationType = GetSelectedCreationType();
            var basicRequest = BasicRequestTextBox.Text?.Trim() ?? "";
            var writingStyle = (WritingStyleComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? "自然流畅";
            var emotionalTone = (EmotionalToneComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? "中性平和";
            var referenceContent = ReferenceContentTextBox.Text?.Trim() ?? "";
            var targetWordCount = TargetWordCountTextBox.Text?.Trim() ?? "2000";

            var prompt = $@"请根据以下要求进行{creationType}：

创作要求：
{basicRequest}

写作要求：
- 目标字数：约{targetWordCount}字
- 写作风格：{writingStyle}
- 情感基调：{emotionalTone}

{(!string.IsNullOrEmpty(referenceContent) ? $@"
参考内容：
{referenceContent}
" : "")}

请确保内容：
1. 符合上述要求和风格
2. 逻辑清晰，结构合理
3. 语言流畅，表达准确
4. 富有创意和吸引力

{GetCreationTypeSpecificInstructions(creationType)}";

            return prompt;
        }

        private string GetSelectedCreationType()
        {
            if (ChapterRadio?.IsChecked == true) return "章节创作";
            if (ContinueRadio?.IsChecked == true) return "续写";
            if (PolishRadio?.IsChecked == true) return "润色";
            if (ExpandRadio?.IsChecked == true) return "扩写";
            if (OutlineRadio?.IsChecked == true) return "大纲生成";
            if (CustomRadio?.IsChecked == true) return "自定义创作";
            return "创作";
        }

        private string GetCreationTypeSpecificInstructions(string creationType)
        {
            return creationType switch
            {
                "章节创作" => "请创作完整的章节内容，包含对话、描写、情节发展等。",
                "续写" => "请自然地延续现有内容，保持风格和逻辑的一致性。",
                "润色" => "请优化语言表达，提升文字质量，保持原意不变。",
                "扩写" => "请在原有基础上增加细节描写、情节发展或背景介绍。",
                "大纲生成" => "请生成结构清晰的大纲，包含主要情节点和章节安排。",
                _ => "请按照要求进行创作。"
            };
        }

        private void UpdateGenerationUI(bool isGenerating)
        {
            GenerateButton.IsEnabled = !isGenerating;
            GenerationProgressBar.IsIndeterminate = isGenerating;
            GenerationProgressBar.Visibility = isGenerating ? Visibility.Visible : Visibility.Collapsed;
        }

        private void Template_Click(object sender, RoutedEventArgs e)
        {
            // TODO: 实现模板功能
            MessageBox.Show("模板功能开发中...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void History_Click(object sender, RoutedEventArgs e)
        {
            // TODO: 实现历史记录功能
            MessageBox.Show("历史记录功能开发中...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(GeneratedContent))
            {
                IsConfirmed = true;
                DialogResult = true;
                Close();
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            IsConfirmed = false;
            DialogResult = false;
            Close();
        }
    }
}
